﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RuYiAdmin.Net.Common.CommonClass.Extensions;
using RuYiAdmin.Net.Common.Global;
using RuYiAdmin.Net.Common.Utility;
using RuYiAdmin.Net.Entity.BusinessEntity.SystemManagement;
using RuYiAdmin.Net.Entity.BusinessEnum;
using RuYiAdmin.Net.Entity.CoreEntity;
using RuYiAdmin.Net.Entity.CoreEnum;
using RuYiAdmin.Net.Service.BusinessService.SystemManagement.Import;
using RuYiAdmin.Net.Service.BusinessService.SystemManagement.Role;
using RuYiAdmin.Net.Service.BusinessService.SystemManagement.RoleMenu;
using RuYiAdmin.Net.Service.BusinessService.SystemManagement.RoleUser;
using RuYiAdmin.Net.WebApi.AppCode.Base;
using RuYiAdmin.Net.WebApi.AppCode.Filter;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace RuYiAdmin.Net.WebApi.Controllers.SystemManagement
{
    /// <summary>
    /// 角色管理接口
    /// </summary>
    public class RoleManagementController : BaseController<SysRole>
    {
        /// <summary>
        /// 角色服务接口实例
        /// </summary>
        private readonly IRoleService roleService;

        /// <summary>
        /// 角色用户服务接口
        /// </summary>
        private readonly IRoleUserService roleUserService;

        /// <summary>
        /// 角色菜单服务接口
        /// </summary>
        private readonly IRoleMenuService roleMenuService;

        /// <summary>
        /// 导入配置服务接口
        /// </summary>
        private readonly IImportConfigService importConfigService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="roleService"></param>
        /// <param name="roleUserService"></param>
        /// <param name="roleMenuService"></param>
        /// <param name="importConfigService"></param>
        public RoleManagementController(IRoleService roleService, IRoleUserService roleUserService,
            IRoleMenuService roleMenuService, IImportConfigService importConfigService) : base(roleService)
        {
            this.roleService = roleService;
            this.roleUserService = roleUserService;
            this.roleMenuService = roleMenuService;
            this.importConfigService = importConfigService;
        }

        /// <summary>
        /// 查询角色列表
        /// </summary>
        /// <param name="queryCondition">查询条件</param>
        /// <returns>ActionResult</returns>
        [HttpPost]
        [Log(OperationType.QueryList)]
        [Permission("role:query:list")]
        public IActionResult Post(QueryCondition queryCondition)
        {
            var actionResult = this.roleService.SqlQuery(queryCondition, "sqls:sql:query_sysrole");
            return Ok(actionResult);
        }

        /// <summary>
        /// 查询角色
        /// </summary>
        /// <param name="roleId">角色编号</param>
        /// <returns>ActionResult</returns>
        [HttpGet("{roleId}")]
        [Log(OperationType.QueryEntity)]
        [Permission("role:query:list")]
        public IActionResult GetById(Guid roleId)
        {
            var actionResult = this.roleService.GetById(roleId);
            return Ok(actionResult);
        }

        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="role">角色对象</param>
        /// <returns>ActionResult</returns>
        [HttpPost]
        [Log(OperationType.AddEntity)]
        [Permission("role:add:entity")]
        public IActionResult Add([FromBody] SysRole role)
        {
            var actionResult = this.roleService.Add(role);
            return Ok(actionResult);
        }

        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <param name="role">角色对象</param>
        /// <returns>ActionResult</returns>
        [HttpPut]
        [Log(OperationType.EditEntity)]
        [Permission("role:edit:entity")]
        public IActionResult Put([FromBody] SysRole role)
        {
            var actionResult = this.roleService.Update(role);
            return Ok(actionResult);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="roleId">角色编号</param>
        /// <returns>ActionResult</returns>
        [HttpDelete("{roleId}")]
        [Permission("role:del:entities")]
        [Log(OperationType.DeleteEntity)]
        public IActionResult Delete(Guid roleId)
        {
            if (this.Check(roleId))
            {
                return BadRequest("role has been used,can not be deleted.");
            }
            var actionResult = this.roleService.Delete(roleId);
            return Ok(actionResult);
        }

        /// <summary>
        /// 批量删除角色
        /// </summary>
        /// <param name="ids">编号数组</param>
        /// <returns>ActionResult</returns>
        [HttpDelete("{ids}")]
        [Permission("role:del:entities")]
        [Log(OperationType.DeleteEntity)]
        public IActionResult DeleteRange(String ids)
        {
            var array = StringUtil.GetGuids(ids);
            foreach (var item in array)
            {
                if (this.Check(item))
                {
                    return BadRequest("role has been used,can not be deleted.");
                }
            }
            var actionResult = this.roleService.DeleteRange(array);
            return Ok(actionResult);
        }

        /// <summary>
        /// 用户授权
        /// </summary>
        /// <param name="roleUsers">用户角色</param>
        /// <returns>ActionResult</returns>
        [HttpPost]
        [Log(OperationType.PermissionAuthorization)]
        [Permission("role:grant:permission")]
        public IActionResult GrantUserRole([FromBody] List<SysRoleUser> roleUsers)
        {
            if (roleUsers.Count > 0)
            {
                var list = (List<SysRoleUser>)this.roleUserService.GetList().Object;
                list = list.Where(t => t.RoleId.Equals(roleUsers.FirstOrDefault().RoleId) && t.IsDel == 0).ToList();
                var ids = list.Select(t => t.Id).ToArray();
                this.roleUserService.DeleteRange(ids);
            }
            var actionResult = this.roleUserService.AddList(roleUsers);
            return Ok(actionResult);
        }

        /// <summary>
        /// 获取授权的角色用户列表
        /// </summary>
        /// <param name="roleId">角色编号</param>
        /// <returns>ActionResult</returns>
        [HttpGet("{roleId}")]
        [Log(OperationType.QueryEntity)]
        [Permission("role:query:list")]
        public IActionResult GetGrantedUserRoles(Guid roleId)
        {
            var list = (List<SysRoleUser>)this.roleUserService.GetList().Object;
            list = list.Where(t => t.RoleId.Equals(roleId) && t.IsDel == 0).ToList();
            var actionResult = new Entity.CoreEntity.ActionResult();
            actionResult.HttpStatusCode = HttpStatusCode.OK;
            actionResult.Message = new String("OK");
            actionResult.Object = list;
            return Ok(actionResult);
        }

        /// <summary>
        /// 角色授权
        /// </summary>
        /// <param name="roleMenus">角色菜单</param>
        /// <returns>ActionResult</returns>
        [HttpPost]
        [Log(OperationType.MenuAuthorization)]
        [Permission("role:relate:menus")]
        public IActionResult GrantRoleMenus([FromBody] List<SysRoleMenu> roleMenus)
        {
            if (roleMenus.Count > 0)
            {
                var list = (List<SysRoleMenu>)this.roleMenuService.GetList().Object;
                list = list.Where(t => t.RoleId.Equals(roleMenus.FirstOrDefault().RoleId) && t.IsDel == 0).ToList();
                var ids = list.Select(t => t.Id).ToArray();
                this.roleMenuService.DeleteRange(ids);
            }
            var actionResult = this.roleMenuService.AddList(roleMenus);
            return Ok(actionResult);
        }

        /// <summary>
        /// 获取授权的角色菜单列表
        /// </summary>
        /// <param name="roleId">角色编号</param>
        /// <returns>ActionResult</returns>
        [HttpGet("{roleId}")]
        [Log(OperationType.QueryEntity)]
        [Permission("role:query:list")]
        public IActionResult GetGrantedRoleMenus(Guid roleId)
        {
            var list = (List<SysRoleMenu>)this.roleMenuService.GetList().Object;
            list = list.Where(t => t.RoleId.Equals(roleId) && t.IsDel == 0).ToList();
            var actionResult = new Entity.CoreEntity.ActionResult();
            actionResult.HttpStatusCode = HttpStatusCode.OK;
            actionResult.Message = new String("OK");
            actionResult.Object = list;
            return Ok(actionResult);
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Log(OperationType.ExportData)]
        [Permission("role:list:export")]
        public IActionResult ExportExcel()
        {
            var data = (List<SysRole>)this.roleService.SqlQuery(new QueryCondition(), "sqls:sql:query_sysrole").List.OrderBy(t => t.Order).ToList();

            var stream = data.Export().ToStream();

            stream.Position = 0;

            return File(stream, "application/octet-stream", "角色信息.xls");
        }

        /// <summary>
        /// Excel导入
        /// </summary>
        /// <param name="file">excel文件</param>
        /// <returns>ActionResult</returns>
        [HttpPost]
        [Log(OperationType.ImportData)]
        [Permission("role:list:import")]
        public IActionResult Import([FromForm] IFormFile file)
        {
            var actionResult = new Entity.CoreEntity.ActionResult();

            if (file != null)
            {
                //获取文件拓展名
                var extension = Path.GetExtension(file.FileName);
                //文件名
                var fileName = Guid.NewGuid() + extension;
                //存储路径
                var path = GlobalContext.DirectoryConfig.GetTempPath() + "/" + fileName;
                //文件读写流
                var stream = new FileStream(path, FileMode.Create);
                //保存文件
                file.CopyTo(stream);
                //关闭流
                stream.Close();

                var configDTO = this.importConfigService.GetImportConfig("RoleImportConfig");

                configDTO.ExcelPath = path;

                var errorCount = 0;// configDTO.ValidationDetecting();

                if (errorCount > 0)
                {
                    actionResult.Object = fileName;
                }

                actionResult.HttpStatusCode = HttpStatusCode.OK;
                actionResult.Message = new String("OK");
            }
            else
            {
                actionResult.HttpStatusCode = HttpStatusCode.NoContent;
                actionResult.Message = new String("NoContent");
            }

            return Ok(actionResult);
        }

        /// <summary>
        /// 角色检测
        /// </summary>
        /// <param name="roleId">角色编号</param>
        /// <returns>真假值</returns>
        private bool Check(Guid roleId)
        {
            var roleUserList = (List<SysRoleUser>)this.roleUserService.GetList().Object;
            var roleMenuList = (List<SysRoleMenu>)this.roleMenuService.GetList().Object;
            if (roleUserList.Where(t => t.RoleId.Equals(roleId) && t.IsDel == 0).Count() > 0
                ||
                roleMenuList.Where(t => t.RoleId.Equals(roleId) && t.IsDel == 0).Count() > 0)
            {
                return true;
            }
            return false;
        }
    }
}
